package commons.base.db;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.druid.pool.DruidDataSource;

public class Databases {

	private static final Logger log = LogManager.getLogger(Databases.class); 
	
	private static Map<String, Database> cache = new HashMap<String, Database>();
	
	static{
		// init
		try {
			String[][] config = {
					 {"local", "kamuy", "localhost", "3306", "root", "123456"}
					,{"132", "kamuy_online_20160408", "10.130.140.132", "3306", "root", "123456"}
					};
			for (String[] ss : config) {
				addDataSource(ss[0], new DataSourceBuilder().setDbName(ss[1]).setHost(ss[2]).setPort(Integer.parseInt(ss[3]))
						.setUsername(ss[4]).setPassword(ss[5]).build());
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
	}
	
	public static void addDataSource(String name, DataSource ds){
		if(!cache.containsKey(name)){
			cache.put(name, new Database(ds));
		}
	}
	
	public static void shutdown(){
		for(Database database : cache.values()){
			try {
				((DruidDataSource)database.getQr().getDataSource()).close();
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
	}
	
	public static Database getDatabase(String name){
		return cache.get(name);
	}
	
}
